import type { RouteRecordRaw } from 'vue-router';
import { isNavigationFailure, Router } from 'vue-router';
import { useAsyncRoute } from '@/store/modules/asyncRoute';
import { useUserContext } from '@/store/modules/user-context';
import { useAccount } from '@/store/modules/account';
import { ErrorPageRoute } from '@/router/base';

export function createRouterGuards(router: Router, asyncRoutes: RouteRecordRaw[]) {
  const asyncRouteStore = useAsyncRoute();
  const userContext = useUserContext();
  const accountStore = useAccount();

  router.beforeEach(async (to, from, next) => {
    const Loading = window['$loading'] || null;
    Loading && Loading.start();

    // 处理尾部斜杠：如果路径以斜杠结尾且不是根路径，则重定向到不带斜杠的版本
    if (to.path !== '/' && to.path.endsWith('/')) {
      const pathWithoutSlash = to.path.slice(0, -1);
      next({ path: pathWithoutSlash, query: to.query, hash: to.hash });
      Loading && Loading.finish();
      return;
    }

    // 保存当前路由的 uniqueStr 到全局状态
    if (to.params.uniqueStr) {
      const uniqueStr = to.params.uniqueStr as string;
      userContext.setUniqueStr(uniqueStr);
      
      // 获取账户信息（带缓存逻辑）
      try {
        await accountStore.getAccountInfoWithCache(uniqueStr);
      } catch (error) {
        console.warn('获取账户信息失败，但不阻止路由跳转:', error);
      }
    }

    // 如果还没有生成菜单，则生成菜单
    if (!asyncRouteStore.getIsDynamicRouteAdded) {
      // 直接设置菜单，不进行权限过滤
      asyncRouteStore.setMenus(asyncRoutes);
      asyncRouteStore.setRouters(asyncRoutes);

      // 添加404页面（在最后，确保它不会过早匹配）
      const isErrorPage = router.getRoutes().findIndex((item) => item.name === ErrorPageRoute.name);
      if (isErrorPage === -1) {
        router.addRoute(ErrorPageRoute);
      }

      asyncRouteStore.setDynamicRouteAdded(true);
    }

    next();
    Loading && Loading.finish();
  });

  router.afterEach((to, _, failure) => {
    document.title = (to?.meta?.title as string) || document.title;
    if (isNavigationFailure(failure)) {
      //console.log('failed navigation', failure)
    }
    const asyncRouteStore = useAsyncRoute();
    // 在这里设置需要缓存的组件名称
    const keepAliveComponents = asyncRouteStore.keepAliveComponents;
    const currentComName: any = to.matched.find((item) => item.name == to.name)?.name;
    if (currentComName && !keepAliveComponents.includes(currentComName) && to.meta?.keepAlive) {
      // 需要缓存的组件
      keepAliveComponents.push(currentComName);
    } else if (!to.meta?.keepAlive || to.name == 'Redirect') {
      // 不需要缓存的组件
      const index = asyncRouteStore.keepAliveComponents.findIndex((name) => name == currentComName);
      if (index != -1) {
        keepAliveComponents.splice(index, 1);
      }
    }
    asyncRouteStore.setKeepAliveComponents(keepAliveComponents);
    const Loading = window['$loading'] || null;
    Loading && Loading.finish();
  });

  router.onError((error) => {
    console.log(error, '路由错误');
  });
}
